import os
import json
import git
Import("env", "projenv")

# access to global construction environment
# print env

# access to project construction environment
# print projenv

# Dump construction environments (for debug purpose)
# print( env.Dump())
# print (projenv.Dump())
js={'lib':{}}
if os.path.exists("build.json"):
    with open("build.json") as fp:
        js=json.load(fp)

for lib in projenv['__PIO_LIB_BUILDERS']:
    repo = git.Repo(lib.path,search_parent_directories=True)
    sha = repo.head.object.hexsha
    print(lib.name,lib.path,sha)
    js['lib'].update({lib.name:{"ID":sha}})

BUILD_NUMBER = os.environ.get('BUILD_NUMBER') or "0"
projenv.Append(CPPDEFINES=[('BUILD_NUMBER', BUILD_NUMBER)])
js['build']=BUILD_NUMBER

# env.Append(ldscript='stm32f103ve.ld')
def before_upload(source, target, env):
    print
    "before_upload"
    # do some actions


def after_upload(source, target, env):
    print
    "after_upload"
    # do some actions


env.AddPreAction("upload", before_upload)
env.AddPostAction("upload", after_upload)

with open("build.json","w+") as fp:
    json.dump(js, fp,indent=2)